package com.devframe.web.taglib;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.Logger;

import com.devframe.sys.util.assertion.Assert;



public class EnumTag extends TagSupport{
	private static Logger logger = Logger.getLogger(EnumTag.class);
	/**默认包*/
	
	/**枚举类名,多个可','隔开*/
	private String enumName;
	
	/**枚举类所在的包名，如果包名为空则值为默认包*/
	private String pakcage;
	/**
	 * 默认的获取枚举得MAP方法，改方法必须是静态方法
	 */
	private static final String DEF_MAP_DATA_METHOD="getMapData";
	/**
	 * MAP数据方法 该方法必须是静态方法，默认是getMapData
	 */
	private String mapDataMethod;
	
	

	public String getPakcage() {
		return pakcage;
	}

	public void setPakcage(String pakcage) {
		this.pakcage = pakcage;
	}

	public String getEnumName() {
		return enumName;
	}

	public void setEnumName(String enumName) {
		this.enumName = enumName;
	}

	private Object getEnumDatas(){
		Class clazz=null;
		try {
			clazz=Class.forName(enumName);
			Method method=clazz.getMethod("getDataMap");
			return method.invoke(clazz);
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		return null;
	}

	public int doStartTag() throws JspException {
		try {
			if(this.pakcage == null){
				this.pakcage = "";
			}
			if(mapDataMethod==null){
				this.mapDataMethod=DEF_MAP_DATA_METHOD;
			}
			if(logger.isDebugEnabled()){
				logger.debug("包名：【"+this.pakcage+"】，MAP方法名：【"+this.mapDataMethod+"】");
			}
			for (String simpleName : this.enumName.split(",")) {
				Class c = Class.forName(this.pakcage+"."+simpleName);
				Method method=c.getDeclaredMethod(this.mapDataMethod);
				Assert.notNull(method,"没找到方法名为【"+this.mapDataMethod+"】");
				Object result=method.invoke(c);
				this.pageContext.setAttribute(simpleName, result);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			Assert.fail(e.getMessage());
		} catch (SecurityException e) {
			e.printStackTrace();
			Assert.fail(e.getMessage());
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
			Assert.fail(e.getMessage());
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			Assert.fail(e.getMessage());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			Assert.fail(e.getMessage());
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			Assert.fail(e.getMessage());
		}
		return SKIP_BODY;
	}
}
